package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/config"
	"yanxue_ai_go/pkg/common/initialize"
	"yanxue_ai_go/pkg/common/logger"
	"yanxue_ai_go/pkg/common/middleware"
	"yanxue_ai_go/services/mcp/internal/handler"
	"yanxue_ai_go/services/mcp/internal/service"
)

func main() {
	// 初始化服务依赖
	initResult, err := initialize.InitializeService("mcp")
	if err != nil {
		logger.Logger.Fatal("Failed to initialize service", zap.Error(err))
	}
	defer initResult.Cleanup()

	// 初始化MCP服务
	mcpService := service.NewMCPService()

	// 初始化路由
	router := setupRouter(initResult.Config, mcpService)

	// 启动服务器
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", 8082), // MCP服务端口
		Handler:      router,
		ReadTimeout:  time.Duration(initResult.Config.Server.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(initResult.Config.Server.WriteTimeout) * time.Second,
		IdleTimeout:  time.Duration(initResult.Config.Server.IdleTimeout) * time.Second,
	}

	// 启动服务器并等待关闭信号
	go func() {
		logger.Logger.Info("MCP service started",
			zap.String("addr", server.Addr),
			zap.String("env", initResult.Config.App.Environment))

		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Logger.Fatal("Failed to start server", zap.Error(err))
		}
	}()

	// 优雅关闭
	shutdownHandler := initialize.NewGracefulShutdown("mcp", server, initResult.Cleanup)
	if err := shutdownHandler.Wait(); err != nil {
		logger.Logger.Error("Shutdown error", zap.Error(err))
	}
}

func setupRouter(cfg *config.Config, mcpService *service.MCPService) *gin.Engine {
	if cfg.App.Environment == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	router := gin.New()

	// 添加中间件
	router.Use(middleware.LoggerMiddleware())
	router.Use(middleware.RecoveryMiddleware())
	router.Use(middleware.CORSMiddleware(
		cfg.Security.CORSAllowedOrigins,
		cfg.Security.CORSAllowedMethods,
		cfg.Security.CORSAllowedHeaders,
	))

	// 健康检查
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"status": "healthy", "service": "mcp"})
	})

	// MCP Protocol路由
	h := handler.NewMCPHandler(mcpService)

	// MCP协议端点
	router.POST("/mcp/initialize", h.Initialize)
	router.POST("/mcp/tools/list", h.ListTools)
	router.POST("/mcp/tools/call", h.CallTool)
	router.POST("/mcp/resources/list", h.ListResources)
	router.POST("/mcp/resources/read", h.ReadResource)
	router.POST("/mcp/prompts/list", h.ListPrompts)
	router.POST("/mcp/prompts/get", h.GetPrompt)

	// REST API路由
	api := router.Group("/api/v1")
	{
		tools := api.Group("/tools")
		{
			tools.GET("", h.GetTools)
			tools.POST("", h.CreateTool)
			tools.GET("/:id", h.GetTool)
			tools.PUT("/:id", h.UpdateTool)
			tools.DELETE("/:id", h.DeleteTool)
		}

		resources := api.Group("/resources")
		{
			resources.GET("", h.GetResources)
			resources.POST("", h.CreateResource)
			resources.GET("/:id", h.GetResource)
			resources.PUT("/:id", h.UpdateResource)
			resources.DELETE("/:id", h.DeleteResource)
		}

		sessions := api.Group("/sessions")
		{
			sessions.GET("", h.GetSessions)
			sessions.POST("", h.CreateSession)
			sessions.GET("/:id", h.GetSession)
			sessions.PUT("/:id", h.UpdateSession)
			sessions.DELETE("/:id", h.DeleteSession)
		}
	}

	return router
}
